import requests
import re


def get_attraction(city: str, weather: str) -> str:
    """
    根据城市和天气，推荐合适的旅游景点（使用百度搜索，不依赖外部API key）。
    """
    try:
        # 构造查询关键词
        query = f"{city}{weather}天去哪里玩 景点推荐"
        url = f"https://www.baidu.com/s?wd={query}"

        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
                          "AppleWebKit/537.36 (KHTML, like Gecko) "
                          "Chrome/118.0.0.0 Safari/537.36"
        }

        response = requests.get(url, headers=headers, timeout=10)
        response.raise_for_status()

        html = response.text

        # 用正则大致提取前几个标题内容
        titles = re.findall(r'<h3 class="t.*?">(.*?)</h3>', html)
        clean_titles = []
        for t in titles:
            t = re.sub(r"<.*?>", "", t)
            if len(t.strip()) > 4:
                clean_titles.append(t.strip())
        if not clean_titles:
            return f"未找到{city}在{weather}天的旅游推荐，请稍后再试。"

        result = "根据当前天气情况，为您推荐以下景点：\n"
        result += "\n".join(f"- {t}" for t in clean_titles[:5])
        return result

    except Exception as e:
        return f"错误: 查询景点时出现问题 - {e}"
